// 防抖
let timer = null
export function debounce(fun, time = 500) {
  return (function () {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(fun, time)
  })()
}

// wgs84转gcj02
const wgs84togcj02 = (lng, lat) => {
  var PI = 3.141592653589793
  var a = 6378245.0
  var ee = 0.006693421622965943

  function transformlng(lng, lat) {
    var ret =
      300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng))
    ret += ((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0) / 3.0
    ret += ((20.0 * Math.sin(lng * PI) + 40.0 * Math.sin((lng / 3.0) * PI)) * 2.0) / 3.0
    ret += ((150.0 * Math.sin((lng / 12.0) * PI) + 300.0 * Math.sin((lng / 30.0) * PI)) * 2.0) / 3.0
    return ret
  }
  function out_of_china(lng, lat) {
    return lng < 72.004 || lng > 137.8347 || lat < 0.8293 || lat > 55.8271 || false
  }

  if (out_of_china(lng, lat)) {
    return [lng, lat]
  } else {
    var dlat = (lng - 105.0, lat - 35.0)
    var dlng = transformlng(lng - 105.0, lat - 35.0)
    var radlat = (lat / 180.0) * PI
    var magic = Math.sin(radlat)
    magic = 1 - ee * magic * magic
    var sqrtmagic = Math.sqrt(magic)
    dlat = (dlat * 180.0) / (((a * (1 - ee)) / (magic * sqrtmagic)) * PI)
    dlng = (dlng * 180.0) / ((a / sqrtmagic) * Math.cos(radlat) * PI)
    var mglat = lat + dlat
    var mglng = lng + dlng
    return [mglng, mglat]
  }
}

// wgs84转高德地图
export const wgs84ToAmap = (AMap, list, type = 'gps') => {
  const defaultTypes = ['gps', 'mapbar', 'baidu']
  if (!defaultTypes.includes(type)) {
    let res = list.map((item) => wgs84togcj02(Number(item[0]), Number(item[1])))
    return Promise.resolve(res)
  }
  return new Promise((resolve) => {
    AMap.convertFrom(list, type, function (status, result) {
      resolve(result.locations)
    })
  })
}

/**
 * 获取时间，带格式
 * @param {Object} params
 * @param {Number} params.timestamp - 时间戳，可传/不穿，默认为当前时间
 * @param {String} params.format - 获取的时间格式，注意中间以空格切分“日期”和“时间”
 *                               - yyyy-MM-dd HH:mm:ss
 *                               - yyyy-MM-dd
 *                               - ...自定义
 */
export function getDate({ timestamp = null, format = 'yyyy-MM-dd HH:mm:ss' } = {}) {
  const addZero = (num, len = 2) => `0${num}`.slice(-len)
  try {
    if (timestamp === 0) {
      return '--'
    }
    let formatDate = ''
    const date = timestamp ? new Date(timestamp) : new Date()
    const objData = {}
    objData.yyyy = date.getFullYear()
    objData.MM = addZero(date.getMonth() + 1)
    objData.dd = addZero(date.getDate())
    objData.HH = addZero(date.getHours())
    objData.mm = addZero(date.getMinutes())
    objData.ss = addZero(date.getSeconds())

    format.split(' ').forEach((time) => {
      formatDate = formatDate.length ? formatDate + ' ' : formatDate
      // 匹配非英文字母
      const other = time.match(/[^A-Za-z]+/g)
      // 匹配非其他字符
      time.match(/[A-Za-z]+/g).forEach((str, key) => {
        formatDate += `${objData[str]}${other[key] || ''}`
      })
    })
    return formatDate
  } catch (e) {
    // console.log(e)
  }
}

export const getConsants = (key, value) => {
  const dicts = JSON.parse(localStorage.getItem('dicts'))
  const item = (dicts[key] || []).find((ele) => ele.constValue === value + '')
  return item?.constLabel || '--'
}

export const getOptions = (keys) => {
  const dicts = JSON.parse(localStorage.getItem('dicts'))
  if (typeof keys === 'string') {
    return dicts[keys].map((item) => ({
      constLabel: item.constLabel,
      constValue: isNaN(item.constValue) ? item.constValue : Number(item.constValue)
    }))
  } else if (Array.isArray(keys)) {
    const res = {}
    keys.forEach((item) => {
      res[item] = dicts[item]
    })
    return res
  }
}
